class CollectionSweeper < ActionController::Caching::Sweeper
  observe Collection, Section

  def after_save(record)
    if record.is_a?(Collection)
      expire_collection(record)
      expire_collections
    elsif record.is_a?(Section)
      expire_collection(record.collection)
    end
  end

  def expire_collection(collection)
    expire_page(:controller => "collections", :action => "show",
      :id => collection.to_param)
    
    # Delete all files in directory to remove all cached pages (pagination)
    pages_path = url_for(:controller=>'collections', :action=>'show',
      :id=>collection.to_param, :page=>'1', :only_path=>true)
    pages_dir = File.join(ActionController::Base.page_cache_directory,
      File.dirname(pages_path))
    Dir.glob(File.join(pages_dir, '*.html')) do |cached_page|
      File.delete(cached_page)
    end
  end
  
  def expire_collections
    expire_page(:controller => 'collections', :action => 'index')
  end
end

